#include "HupProtocal.h"

QByteArray HupProtocal::encode(hup_role_e role, u8 cmd, QByteArray data)
{
	QByteArray frame;
    if (role == EM_HUP_ROLE_MASTER) {
        frame.append(HUP_FRAME_HOST_HDR_H);
        frame.append(HUP_FRAME_HOST_HDR_L);
    }
    else {
        frame.append(HUP_FRAME_CLIENT_HDR_H);
        frame.append(HUP_FRAME_CLIENT_HDR_L);
    }
    frame.append(cmd);

    int data_len = data.size();
    frame.append(data_len & 0xff);
    frame.append((data_len >> 8) & 0xff);

    frame.append(data);

    u8 checksum = cal_xor8(frame);
    frame.append(checksum);

	return frame;
}

u8 HupProtocal::cal_xor8(QByteArray data)
{
    u8 check_sum = 0;
    for (auto byte : data) {
        check_sum ^= byte;
    }
    return check_sum;
}
